package com.slanmao.common.utils;

import com.google.gson.Gson;
import com.slanmao.common.entity.AccessToken;
import com.slanmao.common.entity.UserInfo;
import com.slanmao.exception.CommonException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * <CODE>TokenUtils</CODE>
 *
 * @author fenrir
 * @Date 19-2-28
 */
@Component
@Slf4j
public class TokenUtils {

    @Value("${appid}")
    private String appid;

    @Value("${appsecret}")
    private String appsecret;

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Autowired
    HttpUtils httpUtils;

    private String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";

    private String userinfo_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN";


    public String getAccessToken() throws CommonException {
        String accesstoken = redisTemplate.opsForValue().get("access_token");
        if (StringUtils.isEmpty(accesstoken)) {
            accesstoken = refreshToken();
        }
        return accesstoken;
    }


    public String refreshToken() throws CommonException {
        String response = httpUtils.get(String.format(access_token_url, appid, appsecret));
        AccessToken accessToken = new Gson().fromJson(response, AccessToken.class);
        if (accessToken.getErrcode()!=null){
            log.info("刷新AccessToken失败,"+accessToken.getErrcode()+","+accessToken.getErrmsg());
            throw new CommonException(100002,"刷新AccessToken失败");
        }
        String access_token = accessToken.getAccess_token();
        //保存到redis
        redisTemplate.opsForValue().set("access_token",access_token);
        redisTemplate.expire("access_token",7000, TimeUnit.SECONDS);
        return access_token;
    }



    public UserInfo getUserInfo(String openid) throws CommonException {
        if (openid==null){
            return null;
        }
        String response = httpUtils.get(String.format(userinfo_url, getAccessToken(), openid));
        UserInfo userInfo = new Gson().fromJson(response, UserInfo.class);
        if (userInfo.getErrcode()==null){
            return userInfo;
        }else {
            log.info("获取用户信息错误"+userInfo.getErrcode()+","+userInfo.getErrmsg());
            throw new CommonException(100001,"获取用户信息失败");
        }

    }
}
